using System.Text;
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using Csla.Validation;
using BA.DAL;
using BA;

namespace BlazeApps.Library.Tags
{
    [Serializable()]
    public class Tag : Csla.BusinessBase<Tag>
    {
        private BlazeApps.Library.ConfigSettings Config = new BlazeApps.Library.ConfigSettings();
        private BA.DAL.DBUtility DAL = new BA.DAL.DBUtility();
        private Procedures Procs = new Procedures();

        #region Business Properties and Methods

        //declare members
        private Guid _tagid = Guid.NewGuid();
        private Guid _userid = Guid.Empty;
        private Guid _itemid = Guid.Empty;
        private string _tagname = string.Empty;
        private bool _archived = false;
        private int _ivTagType = 0;

        [System.ComponentModel.DataObjectField(true, false)]
        public Guid Tagid
        {
            get
            {
                CanReadProperty("Tagid", true);
                return _tagid;
            }
        }

        public Guid Userid
        {
            get
            {
                CanReadProperty("Userid", true);
                return _userid;
            }
            set
            {
                CanWriteProperty("Userid", true);
                if (!_userid.Equals(value))
                {
                    _userid = value;
                    PropertyHasChanged("Userid");
                }
            }
        }

        public Guid itemid
        {
            get
            {
                CanReadProperty("itemid", true);
                return _itemid;
            }
            set
            {
                CanWriteProperty("itemid", true);
                if (!_itemid.Equals(value))
                {
                    _itemid = value;
                    PropertyHasChanged("itemid");
                }
            }
        }

        public string Tagname
        {
            get
            {
                CanReadProperty("Tagname", true);
                return _tagname;
            }
            set
            {
                CanWriteProperty("Tagname", true);
                if (value == null)
                    value = string.Empty;
                if (!_tagname.Equals(value))
                {
                    _tagname = value;
                    PropertyHasChanged("Tagname");
                }
            }
        }

        public bool Archived
        {
            get
            {
                CanReadProperty("Archived", true);
                return _archived;
            }
            set
            {
                CanWriteProperty("Archived", true);
                if (!_archived.Equals(value))
                {
                    _archived = value;
                    PropertyHasChanged("Archived");
                }
            }
        }

        public int ivTagType
        {
            get
            {
                CanReadProperty("_ivTagType", true);
                return _ivTagType;
            }
            set
            {
                CanWriteProperty("_ivTagType", true);
                if (!_ivTagType.Equals(value))
                {
                    _ivTagType = value;
                    PropertyHasChanged("_ivTagType");
                }
            }
        }

        protected override object GetIdValue()
        {
            return _tagid;
        }

        #endregion //Business Properties and Methods

        #region Validation Rules
        private void AddCustomRules()
        {
            //add custom/non-generated rules here...
        }

        private void AddCommonRules()
        {
            //
            // Tagname
            //
            ValidationRules.AddRule(CommonRules.StringRequired, "Tagname");
        }

        protected override void AddBusinessRules()
        {
            AddCommonRules();
            AddCustomRules();
        }
        #endregion //Validation Rules

        #region Authorization Rules
        protected override void AddAuthorizationRules()
        {
            //TODO: Define authorization rules in Tag
            //AuthorizationRules.AllowRead("Tagid", "TagReadGroup");
            //AuthorizationRules.AllowRead("Userid", "TagReadGroup");
            //AuthorizationRules.AllowRead("itemid", "TagReadGroup");
            //AuthorizationRules.AllowRead("Tagname", "TagReadGroup");
            //AuthorizationRules.AllowRead("Archived", "TagReadGroup");

            //AuthorizationRules.AllowWrite("Userid", "TagWriteGroup");
            //AuthorizationRules.AllowWrite("itemid", "TagWriteGroup");
            //AuthorizationRules.AllowWrite("Tagname", "TagWriteGroup");
            //AuthorizationRules.AllowWrite("Archived", "TagWriteGroup");
        }


        public static bool CanGetObject()
        {
            //TODO: Define CanGetObject permission in Tag
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("TagViewGroup"))
            //	return true;
            //return false;
        }

        public static bool CanAddObject()
        {
            //TODO: Define CanAddObject permission in Tag
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("TagAddGroup"))
            //	return true;
            //return false;
        }

        public static bool CanEditObject()
        {
            //TODO: Define CanEditObject permission in Tag
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("TagEditGroup"))
            //	return true;
            //return false;
        }

        public static bool CanDeleteObject()
        {
            //TODO: Define CanDeleteObject permission in Tag
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("TagDeleteGroup"))
            //	return true;
            //return false;
        }
        #endregion //Authorization Rules

        #region Factory Methods
        private Tag()
        { /* require use of factory method */
        }

        public static Tag NewTag()
        {
            if (!CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a Tag");
            return DataPortal.Create<Tag>();
        }

        public static Tag GetTag(Guid tagid)
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("User not authorized to view a Tag");
            return DataPortal.Fetch<Tag>(new Criteria(tagid));
        }

        public static void DeleteTag(Guid itemid, Guid UserID, string TagName)
        {
            if (!CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a Tag");
            DataPortal.Delete(new Criteria(itemid, UserID, TagName));
        }

        public override Tag Save()
        {
            if (IsDeleted && !CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a Tag");
            else if (IsNew && !CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a Tag");
            else if (!CanEditObject())
                throw new System.Security.SecurityException("User not authorized to update a Tag");

            return base.Save();
        }

        #endregion //Factory Methods

        #region Data Access

        #region Criteria

        [Serializable()]
        private class Criteria
        {
            public Guid ItemID;
            public Guid UserID;
            public string TagName;

            public Criteria(Guid ItemID)
            {
                this.ItemID = ItemID;
            }

            public Criteria(Guid ItemID, Guid UserID, string TagName)
            {
                this.ItemID = ItemID;
                this.UserID = UserID;
                this.TagName = TagName;
            }
        }

        #endregion //Criteria

        #region Data Access - Create
        [RunLocal]
        protected override void DataPortal_Create()
        {
            ValidationRules.CheckRules();
        }

        #endregion //Data Access - Create

        #region Data Access - Fetch
        private void DataPortal_Fetch(Criteria criteria)
        {
            ExecuteFetch(criteria);
        }

        private void ExecuteFetch(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            DAL.AddParameter("@tagid", _tagid);

            using (SafeDataReader dr = new SafeDataReader(DAL.ExecuteReader("usp_get_page_byid", CommandType.StoredProcedure, ConnectionState.Open)))
            {
                FetchObject(dr);
                ValidationRules.CheckRules();

                //load child object(s)
                FetchChildren(dr);
            }
        }

        private void FetchObject(SafeDataReader dr)
        {
            dr.Read();
            _tagid = dr.GetGuid("tagid");
            _userid = dr.GetGuid("userid");
            _itemid = dr.GetGuid("itemid");
            _tagname = dr.GetString("tagname");
            _archived = dr.GetBoolean("archived");
            _ivTagType = dr.GetInt32("iv_tagtype");
        }

        private void FetchChildren(SafeDataReader dr)
        {
        }
        #endregion //Data Access - Fetch

        #region Data Access - Insert
        protected override void DataPortal_Insert()
        {
            ExecuteInsert();
        }

        private void ExecuteInsert()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddInsertParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.InsertTag.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddInsertParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@tagid", _tagid);
            DAL.AddParameter("@userid", _userid);
            DAL.AddParameter("@itemid", _itemid);
            DAL.AddParameter("@tagname", _tagname);
            DAL.AddParameter("@ivtagtype", _ivTagType);

            if (_archived != false)
                DAL.AddParameter("@archived", _archived);
            else
                DAL.AddParameter("@archived", 0);
        }
        #endregion //Data Access - Insert

        #region Data Access - Update
        protected override void DataPortal_Update()
        {
            if (base.IsDirty)
            {
                ExecuteUpdate();
            }
        }

        private void ExecuteUpdate()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddUpdateParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.UpdateTag.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddUpdateParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@tagid", _tagid);
            DAL.AddParameter("@userid", _userid);
            DAL.AddParameter("@itemid", _itemid);
            DAL.AddParameter("@tagname", _tagname);
            DAL.AddParameter("@ivtagtype", _ivTagType);

            if (_archived != false)
                DAL.AddParameter("@archived", _archived);
            else
                DAL.AddParameter("@archived", 0);
        }

        private void UpdateChildren(SqlConnection cn)
        {
        }
        #endregion //Data Access - Update

        #region Data Access - Delete
        protected override void DataPortal_DeleteSelf()
        {
            DataPortal_Delete(new Criteria(_tagid));
        }

        private void DataPortal_Delete(Criteria criteria)
        {
            ExecuteDelete(criteria);
        }

        private void ExecuteDelete(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddDeleteParameters(ref DAL, criteria);

            DAL.ExecuteNonQuery(Procs.DeleteTag.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddDeleteParameters(ref BA.DAL.DBUtility DAL, Criteria criteria)
        {
            DAL.AddParameter("@tagname", criteria.TagName);
            DAL.AddParameter("@itemid", criteria.ItemID);
            DAL.AddParameter("@userid", criteria.UserID);
            DAL.AddParameter("@archived", 1);
        }
        #endregion //Data Access - Delete
        #endregion //Data Access
    }
}
